package zju.ccnt.fileserverProxy.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import zju.ccnt.fileserverProxy.repository.FileServerRepository;

import java.util.*;

/**
 * Created by zha on 14/11/27.
 */
@Component(value = "scoreStrategyFileServerLoadBalance")
public class ScoreStrategyFileServerLoadBalance implements FileServerLoadBalance {

    FileServerRepository fileServerRepository;

    class SimpleFileServer implements Comparable<SimpleFileServer>{
        private long timeInterval;
        private int availableCapacity;
        private String postUrl;

        public SimpleFileServer(long timeInterval, int availableCapacity, String postUrl){
            this.timeInterval = timeInterval;
            this.availableCapacity = availableCapacity;
            this.postUrl = postUrl;
        }

        private long score(){
            return availableCapacity - timeInterval * 5;
        }

        @Override
        public int compareTo(SimpleFileServer o) {
            long res = this.score() - o.score();
            return res >= 0 ? -1 : 1;
        }

        public String getPostUrl() {
            return postUrl;
        }
    }

    @Autowired
    public ScoreStrategyFileServerLoadBalance(FileServerRepository fileServerRepository){
        this.fileServerRepository = fileServerRepository;
    }

    @Override
    public String selectFileServer(int size) {
        List<String> allServerNames = fileServerRepository.getAllFileServerName();
        List<SimpleFileServer> servers = new ArrayList<SimpleFileServer>();
        long currentTime = System.currentTimeMillis();
        for (String serverName: allServerNames){
            SimpleFileServer fileServer = buildSimpleFileServer(serverName, currentTime);
            if (fileServer.availableCapacity > size) servers.add(fileServer);
        }
        Collections.sort(servers);
        if (servers.size() == 0) return null;
        return servers.get(0).getPostUrl();
    }

    private SimpleFileServer buildSimpleFileServer(String serverName, long currentTime){
        Map<String, String> server = fileServerRepository.getFileServerDetail(serverName);
        long timeStamp = Long.parseLong(server.get("timestamp"));
        int size = Integer.parseInt(server.get("size"));
        int capacity = Integer.parseInt(server.get("capacity"));
        return new SimpleFileServer(currentTime - timeStamp, capacity-size, server.get("postUrl"));
    }

}
